package com.itboye.services.utils.impl;

import com.itboye.mybatis.enumtype.CodeType;
import com.itboye.mybatis.mapper.IBaseMapper;
import com.itboye.mybatis.mapper.ISecurityCodeMapper;
import com.itboye.mybatis.model.SecurityCodeModel;
import com.itboye.services.ucenter.BaseService;
import com.itboye.services.utils.interfaces.ISecurityCodeService;
import com.itboye.system.bean.ByResultBean;
import com.itboye.system.helper.ByConsoleHelper;
import com.itboye.system.helper.ByDateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * SecurityCodeService.java
 * Created on  2016/7/29 10:52
 * 版本       修改时间          作者      修改内容
 * V1.0.1    2016/7/29      hebidu    初始版本
 * <p>
 * Copyright (c) 2013 杭州博也网络科技有限公司 版权所有
 * HANGZHOU BOYE TECHNOLOGY CO.,LTD. All Rights Reserved.
 */
@Service("securityCodeService")
public class SecurityCodeService extends BaseService<SecurityCodeModel> implements ISecurityCodeService {

    public IBaseMapper<SecurityCodeModel> getMapper() {
        return securityCodeMapper;
    }

    public SecurityCodeService() {
        super();
        ByConsoleHelper.debug("SecurityCodeService init",logger);
    }

    @Resource
    private ISecurityCodeMapper securityCodeMapper;

    private static final Logger logger = LogManager.getLogger(SecurityCodeService.class.toString());

    /**
     * 验证安全码是否有效
     * @param  code 安全码
     * @param accepter 接受者
     * @param codeType 安全码类型
     * @return
     */
    public ByResultBean isValid(String code, String accepter, CodeType codeType) {

        HashMap<String,String> params = new HashMap<String, String>();

        params.put("code",code);
        params.put("accepter",accepter);
        params.put("type",""+codeType.getValue());
        params.put("timestamp", "" + ByDateHelper.getCurrentTimeStamp());

        SecurityCodeModel model = securityCodeMapper.getInfoBy(params);

        if(model == null){
            return ByResultBean.fail("验证码验证失败!");
        }

        //使同一手机号,同一类型的验证码 都无效化
        params.clear();
        params.put("accepter",accepter);
        params.put("code",""+codeType.getValue());
        params.put("status","1");

        int effectRows =  securityCodeMapper.update(params);

        ByConsoleHelper.debug("验证码去除重复="+effectRows,logger);

        return ByResultBean.success("验证成功");
    }

}
